package com.boyuan.aboutcase;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.boyuan.huijiaoyu.R;
import com.boyuan.huijiaoyu.R.layout;
import com.example.newfragment.CaseListEntity;
import com.magicsoft.app.entity.CaseDetailEntity;
import com.magicsoft.app.entity.TrendsEntity;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.CaseService;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.constant.Constant;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 * 
 */
public class DynamicFragment extends Fragment {

	private String tag = "DynamicFragment";
	private MyReceiver myReceiver;
	private List<TrendsEntity> Trendslist = new ArrayList<TrendsEntity>();
	private List<TrendsEntity> Trendslist2 = new ArrayList<TrendsEntity>();
	private MyAdapter myAdapter;
	private ListView mListView;
	private CaseService caseService;
	private String yonghuID;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_dynamic, container,
				false);
		SharedPreferences sp = getActivity().getSharedPreferences("a.xml", 0);
		yonghuID = sp.getString("username", "");
		InitUI(view);
		return view;
	}

	private void InitUI(View view) {
		mListView = (ListView) view.findViewById(R.id.listView_dynamic);
		myAdapter = new MyAdapter();
		mListView.setAdapter(myAdapter);
		setAbsListViewHeightBasedOnChildren(mListView);

		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.GETDYNAMIC);
		myReceiver = new MyReceiver();
		getActivity().registerReceiver(myReceiver, filter);
	}

	class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			CaseDetailEntity caseDetailEntity = (CaseDetailEntity) intent
					.getSerializableExtra("caseDetailEntity");
			Trendslist.clear();
			Trendslist = caseDetailEntity.getTrends();
			myAdapter.notifyDataSetChanged();
			setAbsListViewHeightBasedOnChildren(mListView);
		}
	}

	class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return Trendslist.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(final int position, View contenview,
				ViewGroup parent) {
			View view = null;
			ViewHolder viewHolder = null;
			if (contenview == null) {
				viewHolder = new ViewHolder();
				view = getActivity().getLayoutInflater().inflate(
						R.layout.dynamic_listitem, null);
				viewHolder.tv_creater_dynamic_ltem = (TextView) view
						.findViewById(R.id.tv_creater_dynamic_ltem);
				viewHolder.tv_creater_dynamic_desc = (TextView) view
						.findViewById(R.id.tv_creater_dynamic_desc);
				viewHolder.tv_creater_dynamic_time = (TextView) view
						.findViewById(R.id.tv_creater_dynamic_time);
				viewHolder.tv_creater_dynamic_delete = (TextView) view
						.findViewById(R.id.tv_creater_dynamic_delete);
				view.setTag(viewHolder);
			} else {
				view = contenview;
				viewHolder = (ViewHolder) view.getTag();
			}
			
//			//实现倒序
			TrendsEntity trendsEntity = Trendslist.get(position);
//			Trendslist2.clear();
//			Object[] array = Trendslist.toArray();
//			for (int i = array.length-1; i >=0; i--) {
//				Trendslist2.add((TrendsEntity)array[i]);
//			}
//			Log.e("Trendslist2", Trendslist2.toString());
//			TrendsEntity trendsEntity = Trendslist2.get(position);
			
			// 获取数据
			String creater = trendsEntity.getCreater();
			String content = trendsEntity.getContent();
			String createtime = trendsEntity.getCreatetime();
			String creater_id = trendsEntity.getCreater_id();
			final String get_id = trendsEntity.getId();
			// 进行显示动态数据
			viewHolder.tv_creater_dynamic_ltem.setText(creater);
			viewHolder.tv_creater_dynamic_desc.setText(content);
			if(!"".equals(createtime)){
				String month = createtime.substring(4, 6);
				String day = createtime.substring(6, 8);
				String hours = createtime.substring(8, 10);
				String mins = createtime.substring(10, 12);
				viewHolder.tv_creater_dynamic_time.setText(month + "-" + day + " "
						+ hours + ":" + mins);
			}else{
				viewHolder.tv_creater_dynamic_time.setText("");
			}
			if ("0".equals(creater_id)) {
				viewHolder.tv_creater_dynamic_delete
						.setVisibility(View.INVISIBLE);
			}else if(yonghuID.equals(creater_id)){
				viewHolder.tv_creater_dynamic_delete
				.setVisibility(View.VISIBLE);
				viewHolder.tv_creater_dynamic_delete
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						deleteTrends(get_id, position);
					}
				});
			}else {
				viewHolder.tv_creater_dynamic_delete
				.setVisibility(View.INVISIBLE);
		}
			return view;
		}
	}

	private void deleteTrends(String trend_id, final int position) {
		if (caseService == null) {
			caseService = new CaseService(getActivity());
		}
		SharedPreferences sp = getActivity().getSharedPreferences("a.xml", 0);
		String corp_id = sp.getString("username", "");
		String operator = sp.getString("realname", "");

		caseService.deleteCaseTrend("1", trend_id, corp_id, operator,
				new PostRecordResponseListener() {

					@Override
					public void onFinish(String succString) {
//						Trendslist2.remove(position);
//						myAdapter.notifyDataSetChanged();
						Intent intent = new Intent();
						intent.setAction(Constant.DELTRENDS);
						getActivity().sendBroadcast(intent);
						ToastHelper.showMsg(getActivity(), succString, false);
//						setAbsListViewHeightBasedOnChildren(mListView);
					}

					@Override
					public void onFailed(String failString) {
						ToastHelper.showMsg(getActivity(), failString, false);
					}
				});
	}

	/**
	 * 动态计算设置AbsListView高度
	 * 
	 * @函数名 setAbsListViewHeightBasedOnChildren
	 * @功能 TODO
	 * @param absListView
	 * @备注 <其它说明>
	 */

	private void setAbsListViewHeightBasedOnChildren(AbsListView absListView) {
		ListAdapter listAdapter = absListView.getAdapter();
		if (listAdapter != null && listAdapter.getCount() > 0) {

			int count = listAdapter.getCount();
			View view = listAdapter.getView(0, null, absListView);
			view.measure(0, 0);
			int totalHeight = 0;

			if (absListView instanceof ListView) {

				totalHeight = (view.getMeasuredHeight() + 1) * count;
			} else if (absListView instanceof GridView) {

				totalHeight = view.getMeasuredHeight() * ((count - 1) / 4 + 1);
			}

			ViewGroup.LayoutParams params = absListView.getLayoutParams();
			params.height = totalHeight;
			absListView.setLayoutParams(params);
		} else {
			ViewGroup.LayoutParams params = absListView.getLayoutParams();
			params.height = 0;
			absListView.setLayoutParams(params);
		}
	}

	class ViewHolder {
		TextView tv_creater_dynamic_ltem;
		TextView tv_creater_dynamic_desc;
		TextView tv_creater_dynamic_time;
		TextView tv_creater_dynamic_delete;
	}
}
